package com.taplinker.client.crm.rpc;

import android.text.TextUtils;
import android.widget.Toast;

import com.google.protobuf.InvalidProtocolBufferException;
import com.taplinker.client.AppConfigContext;
import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.crm.domain.CrmDataCenter;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.rpc.command.SimpleBaseCommand;
import com.taplinker.core.rpc.http.HttpTemplate;
import com.taplinker.dto.web.CustomerProto.CustomerList_V2;
import com.taplinker.dto.web.FindCustomerProto;
import com.taplinker.dto.web.FindCustomerProto.FindCustomer.Builder;
/**
 * 获取用户
 * @author djbian
 *
 */
public class GetCustomersCmd extends SimpleBaseCommand {

	private String type = "";
	private String key = "";
	private int index = CrmDataCenter.getInstance().getList().size();

	public GetCustomersCmd(String type) {
		this.type = type;
	}

	public GetCustomersCmd(String type,final int index) {
		this.type = type;
		this.index = index;
	}

	public GetCustomersCmd(String type, String key,int index) {
		this.type = type;
		CrmDataCenter.getInstance().clearList();
		this.key = key;
		this.index = index;
	}

	@Override
	public Result go() {
		Builder b = FindCustomerProto.FindCustomer.newBuilder();
		b.setSource(type);
		if (!TextUtils.isEmpty(key)) {
			b.setQueryKey(key);
		}
		b.setSkip(index);
		b.setLimit(10);
		b.setUserId((int) AppConfigFactory.getInstance().getUserInfo().getUserid());
		return new HttpTemplate().postForGogoByte(AppConfigContext.TAPLINKER_WEB
				+ "/services/crm/v2/user/info/customers", b.build().toByteArray());
	}

	@Override
	public void yes(Result result) {
		super.yes(result);
		try {
			CustomerList_V2 list = CustomerList_V2.parseFrom((byte[]) result.object);
			CrmDataCenter.getInstance().addCustomerList(list.getCustomerList());
			int i = 2;
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		CrmDataCenter.getInstance().noticeListener(CrmDataCenter.GET_CUSTOMERS_CMD);
	}
	
	@Override
	public void no(Result result) {
		Toast.makeText(CrmDataCenter.getInstance().getContext(), "网络异常，请稍侯再试！", Toast.LENGTH_LONG).show();
	}
}
